<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\CarDealer;

use AuctionBack\Service\ThriftBailService;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\CarResource\Car;
use AuctionCore\Cashier\Collection;
use AuctionCore\Cashier\Payment;
use AuctionCore\System\SystemConf;
use AuctionCore\System\AuctionException;
use Think\Log;

/**
 * 资产中心功能类
 *
 * @author  Eric Lee
 */
class AssetCenter
{

    private $dealer_id = null;

    /**
     * AssetCenter constructor.
     * @param string $dealer_id
     */
    public function __construct($dealer_id = '')
    {
        $this->dealer_id = $dealer_id;
    }

    public function add($data)
    {
        $bailLog = [
            'dealer_id' => $data['dealer_id'],
            'use_type' => $data['use_type'],
            'use_detail' => $data['use_detail'],
            'occur_money' => $data['occur_money'],
            'recharge_method' => $data['recharge_method'],  //充值方式
            'remain_amount' => $data['remain_amount'], //余额
            'createtime' => $data['createtime'],
            'use_time' => $data['createtime'],
            'collection_id' => $data['collection_id']
        ];
        return M('dealer_bail_log')->add($bailLog);
    }

    /**
     * 保证金情况
     * @return array (保证金总额，可用保证金，冻结保证金，累计赔付金额)
     */
    public function bailSituation()
    {
        $cols = "bail_amount, bail_amount AS available_amount ,freeze_amount, indemnity_amount,minus_amount";
        $map = ["dealer_id" => $this->dealer_id];
        return M('car_dealer')->field($cols)
            ->where($map)
            ->find();
    }

    /**
     * 保证金充值：记录充值日志，并计算可用额度和冻结额度并计算可用额度和冻结额度
     * 返回array
     * @param int $occur_money 发生金额
     * @param int $recharge_method 充值方式1支付宝 2拉卡拉 3线下充值 4网银 5代金券
     * @param string $msg 备注信息
     * @return array $ret (可用额度,冻结额度
     */
    public function bail_recharge($data)
    {
        $occur_money = $data['occur_money'];
        $dealer_id = $this->dealer_id;

        if (!is_numeric($dealer_id) || $dealer_id <= 0) {
            AuctionException::make_throw('500001');
        }
        if (!is_numeric($occur_money) || $occur_money <= 0) {
            AuctionException::make_throw('500004');
        }
        if ((int)$occur_money != $occur_money) {
            AuctionException::make_throw('500016');
        }

        $now = date("Y-m-d H:i:s", time());
        $dealer_info = $this->bailSituation();

        //开启事务
        M()->startTrans();
        $collectionData = [
            'payment_type' => 5, //收款类型 保证金充值
            'payment_method' => 1,
            'amount' => $occur_money,
            'status' => 1,
            'create_time' => $now,
            'update_time' => $now,
            'emp_id' => $data['emp_id'],
            'emp_name' => $data['emp_name'],
        ];
        $collection_id = Collection::add($collectionData);
        if ($collection_id < 1) {
            Log::record("保证金充值，添加收款单失败,车商ID[$dealer_id]", "ERR", true);
            M()->rollback();
            AuctionException::make_throw('500067');
        }

        /**保证金充值**/
        $bail = new ThriftBailService();
        $bail_state = $bail->incBail($dealer_id, $occur_money, $data['use_detail'], '',  0, $data['recharge_method'], $collection_id);
        if ($bail_state->code != '000000') {
            Log::record("保证金充值，更新车商保证金总数失败,车商ID[$dealer_id]", "ERR", true);
            M()->rollback();
            AuctionException::make_throw('500067');
        }

        $dealerModel = M('car_dealer');
        M()->commit();
        //维修保养记录结算

        $this->check_minus($dealer_id);
        //保证金信息
        $ret = $dealerModel->field('dealer_id,bail_amount,freeze_amount')->find($dealer_id);
        return $ret;
    }

    /**
     * 充值时检查维保透支情况并结算
     * @param $dealer_id
     * @return bool
     */
    private function check_minus($dealer_id)
    {
        $credit_lines = SystemConf::getConfByName("REPAIR_CREDIT_LINES");
        $single_price = SystemConf::getConfByName("REPAIR_SINGL_PRICE");
        $credit_lines = $credit_lines['value'];
        $single_price = $single_price['value'];
        $now = date("Y-m-d H:i:s");
        $use_type = 8;
        $dealer_bail = true;

        $dealer_info = $this->bailSituation();
        $minus_amount = $dealer_info['minus_amount'];
        if ($minus_amount == $credit_lines && $dealer_info['bail_amount'] >= $single_price) {
            $repair = new \AuctionCore\CarDealer\RepairCheck();
            $last_amount = $log_list = 0;
            $use_money = $minus_amount;
            $bail_amount = $dealer_info['bail_amount'] - $minus_amount;
            //判断充值后余额是否大于维保透支
            if ($dealer_info['bail_amount'] < $minus_amount) {
                //计算修改状态日志条数
                $log_list = intval($dealer_info['bail_amount'] / $single_price);
                $last_amount = $minus_amount - ($single_price * $log_list);
                $bail_amount = intval(fmod(floatval($dealer_info['bail_amount']), $single_price));
            }
            if ($last_amount != 0) {
                $use_money = $single_price * $log_list;
            }

            $dealer = new Dealer($dealer_id);
            //开启事务
            M()->startTrans();
            $collection_no = genBillsNo('SK', 9);
            $colle_state = AssetCenter::collection_log($collection_no, $use_money, 9);
            if ($colle_state < 1) {
                Log::record("维保结算，添加收款单失败", "ERR", true);
                return false;
            }

            $bail = new ThriftBailService();
            $bail_state = $bail->decBail($dealer_id, $use_money, $use_type, '查询维修保养扣款', 0, 0, 0, $colle_state);
            if ($bail_state->code != '000000') {
                $dealer_bail = false;
            }
            $bail_log = AssetCenter::last_bail_log($dealer_id, $use_money, $use_type);//获取最新日志log
            $dealer->edit(array('minus_amount' => $last_amount)); //修改用户授权额度和可用保证金
            $repair->the_bill($use_money, $bail_log, $log_list,$dealer_id);  //结算操作
            if ($dealer_bail) {
                M()->commit();
                return true;
            } else {
                M()->rollback();
                return false;
            }
        }
        return true;
    }


    /**
     * 保证金提取：记录提取日志，并计算可用额度和冻结额度并计算可用额度和冻结额度
     * 返回array(可用额度,冻结额度
     *
     * @param int $extract_money 发生金额
     * @param int $extract_method 充值方式1支付宝 2拉卡拉 3线下充值 4网银 5代金券
     * @param string $msg 备注信息
     * @param int $emp_id 操作人ID
     * @param string $emp_name 操作人姓名
     *
     * @return array
     */
    public function bail_extract($extract_money, $extract_method = 3, $msg = '保证金提取', $emp_id = 0, $emp_name = '')
    {
        $dealer_id = $this->dealer_id;

        if (!is_numeric($dealer_id) || $dealer_id <= 0) {
            AuctionException::make_throw('500001');
        }
        if (!is_numeric($extract_money) || $extract_money <= 0) {
            AuctionException::make_throw('500004');
        }
        if ((int)$extract_money != $extract_money) {
            AuctionException::make_throw('500016');
        }
        $now = date("Y-m-d H:i:s", time());
        $dealer_info = $this->bailSituation();
        if ($extract_money > $dealer_info['bail_amount'] - $dealer_info['minus_amount']) {
            AuctionException::make_throw('500015');
        }
        //开启事务
        M()->startTrans();
        //添加付款单
        $paymentData = [
            'status' => 1,
            'pay_type' => 8, //保证金提取
            'pay_way' => 1,
            'amount' => $extract_money,
            'emp_id' => $emp_id,
            'emp_name' => $emp_name,
            'card_no' => '',
            'bank_name' => '',
            'account_name' => '',
            'create_time' => $now,
            'update_time' => $now,
        ];
        $paymentId = Payment::add($paymentData);
        if ($paymentId < 1) {
            M()->rollback();
            Log::record("保证金提取，添加付款单失败，dealer_id: $dealer_id", "ERR", true);
            AuctionException::make_throw('500015');
        }
        $bail = new ThriftBailService();
        $bail_state = $bail->decBail($dealer_id, $extract_money, 4, $msg, 0, $extract_method, $paymentId);
        if ($bail_state->code != '000000') {
            M()->rollback();
            Log::record("保证金提取，添加付款单失败，dealer_id: $dealer_id", "ERR", true);
            AuctionException::make_throw('500015');
        }
        M()->commit();
        //保证金信息
        $dealer = M('car_dealer');
        $ret = $dealer->field('dealer_id,bail_amount,freeze_amount')->find($dealer_id);
        return $ret;
    }

    /**
     * 保证金日志列表 根据条件返回保证金使用列表，默认时间倒序
     *
     * @param int $page
     * @param int $limit
     * @param array $params
     * @return array
     */
    public function get_bail_logs($page = 1, $limit = 5, $params)
    {
        $page = (int)$page < 1 ? 1 : $page;
        $limit = (int)$limit < 1 ? 5 : $limit;
        $map = array();
        $map['dealer_id'] = array('eq', $this->dealer_id);
        //保证金使用类型
        if (!empty($params['use_type'])) {
            $useType = $params['use_type'];
        }
        //发生时间
        if (!empty($params['use_time']) && strtotime($params['use_time'])) {
            $useTime = $params['use_time'];
        }
        //是否解冻
        if (isset($params['is_free']) && $params['is_free'] > -1) {
            $isFree = $params['is_free'];
        }
        $bail = new ThriftBailService();
        $result = $bail->getBailLogsByDealerId($this->dealer_id, $useType, $useTime, $page, $limit, $isFree, 0);
        $logs = array();
        $total = 0;
        if ($result->code == '000000') {
            $logs = json_decode($result->data['logs'], true);
            $total = $result->data['nums'];
            foreach ($logs as $k => $v) {
                $order_no = M('order')->where("order_id='" . $v['order_id'] . "'")->getField('order_no');
                switch ($v['use_type']) {
                    case '1':
                        $msg = '充值';
                        break;
                    case '2':
                        $msg = '对拍单【' . $order_no . '】  进行出价， 冻结保证金。';
                        break;
                    case '3':
                        $msg = '解冻出价保证金，拍单【' . $order_no . '】';
                        break;
                    // case '4':$msg = '提取，拍单【'.$order_no.'】';break;
                    case '4':
                        $msg = '提取';
                        break;
                    case '5':
                        $msg = '争议支出。拍单【' . $order_no . '】';
                        break;
                    case '6':
                        $msg = '违约赔付保证金。拍单【' . $order_no . '】';
                        break;
                    case '7':
                        $msg = '其它';
                        break;
                    case '8':
                        $msg = '车辆维保信息查询透资，金额扣除。';
                        break;
                    default:
                        ;
                }
                $v['use_detail'] = $msg;
                $logs[$k] = $v;
            }
        }
        $res = array(
            'logs' => $logs,
            'total' => $total
        );
        return $res;
    }

    /**
     * 查询日志总数
     *
     * @param    String $condition 条件
     *
     * @return   int 条数
     */
    public function get_bail_log_count($condition = false)
    {
        $condition = trim($condition);
        $dealer_id = $this->dealer_id;
//      if($dealer_id){
//         $condition = " dealer_id = '{$dealer_id}' ".($condition?' and '.$condition:'');
//      }
        //$condition ='';
        $num = M('dealer_bail_log')->where($condition)->count();
        return $num;
    }

    /**
     * 代金券列表，，默认时间倒序
     *
     * @param    int $cond 条件
     * @param    int $offset 偏移量
     * @param    int $limit 限制
     *
     * @return   Array
     */
    public function get_coupons($cond, $order = 'dc.createtime desc', $offset = '0', $limit = '20')
    {
        $res = M('dealer_coupon')->alias('dc')
            ->join(C('DB_PREFIX') . "coupon c on c.coupon_id=dc.coupon_id")
            ->field("dc.*,c.emp_id as c_emp_id,c.title,c.type,c.status as c_status")
            ->where("dc.dealer_id='" . $this->dealer_id . "'")->where($cond)->order($order)->limit($offset, $limit)->select();
        return $res;
    }

    /**
     * 冻结车商保证金
     *
     * @param 车商id
     * @param int          order_id 使用保证金的拍单id
     * @param $msg         保证金使用描述
     * @param $occur_money 冻结金额
     *
     * @return true/false   成功、失败
     */
    public function freeze($order_id, $occur_money = 2000, $msg)
    {
        if (!is_numeric($order_id) || $order_id <= 0) {
            AuctionException::make_throw('500055');
        }
        $dealer_id = $this->dealer_id;

        /**Thrift服务 冻结**/
        $bail = new ThriftBailService();
        $bail_state = $bail->freezeBail($dealer_id, $occur_money, $order_id);
        if ($bail_state->code != '000000') {
            AuctionException::make_throw('500052');
        }
        return true;
//        $bail_log = M('dealer_bail_log');
//        /*
//          $info = $bail_log->query("SELECT SUM(IF(use_type=2,occur_money,0)) AS freeze_amount,SUM(IF(use_type=3,occur_money,0)) AS free_amount FROM au_dealer_bail_log WHERE dealer_id='{$dealer_id}' and order_id='{$order_id}';");
//          if($info && ($info[0]['freeze_amount']>$info[0]['free_amount'])){
//          //是否已经冻结
//          return true;
//          } */
//        //todo 开发机已经测试通过.................................
//        $prefix = C('DB_PREFIX');
//        $rows = M()->query("SELECT `occur_money` freze_money FROM `{$prefix}dealer_bail_log` WHERE `order_id`='{$order_id}' AND `dealer_id`='{$dealer_id}' AND `use_type`=2 AND is_free=0;");
//        if ($rows && count($rows) > 0 && $rows[0]['freze_money'] > 0) {
//            //是否已经冻结
//            return true;
//        }
//
//        //生成冻结描述
//        /* $row = M()->query("SELECT CONCAT('对拍品  【',pad.`city_name`,ad.`city_name`,'】 ',mb.`name` ,' ',s.`name` ,m.`name`,' 进行出价，冻结保证金。') msg
//          FROM  au_order o
//          LEFT JOIN au_cars car ON car.car_id = o.`car_id`
//          LEFT JOIN au_addr_area ad ON car.reg_city=ad.city_code
//          LEFT JOIN au_addr_area pad ON ad.pid=pad.city_code
//          LEFT JOIN au_car_model m ON car.`model_id` = m.`model_id`
//          LEFT JOIN `au_car_series` s ON m.`series_id` = s.`series_id`
//          LEFT JOIN au_car_brand b ON s.`brand_id` = b.`brand_id`
//          LEFT JOIN au_car_mbrand mb ON b.`mbrand_id` = mb.`mbrand_id`
//          WHERE  o.`order_id` = {$order_id} ;"); */
//        if (!$msg) {
//            $row = M()->query("SELECT CONCAT('对拍单【',o.order_no,',',car.car_id,'】 ',' 进行出价， 冻结保证金。') msg
//               FROM  au_order o
//               INNER JOIN au_cars car ON car.car_id = o.`car_id`
//               WHERE  o.`order_id` = '" . $order_id . "'");
//            if (count($row) > 0) {
//                $msg = $row[0]['msg'];
//            }
//        }
//
//        //车商信息
//        $dealer = new Dealer($dealer_id);
//        $dealer_info = $dealer->dealer_base_info();
//        if ($dealer_info['bail_amount'] < $occur_money) { //保证金不足
//            AuctionException::make_throw('500051');
//        }
//
//
//        //保证金使用记录
//        $remain_amount = ($dealer_info['bail_amount'] - $occur_money);
//        $bail_log_info = array(
//            'dealer_id' => $dealer_id //int(10)车商id
//        , 'order_id' => $order_id //int(10)拍单号
//        , 'use_time' => $now //datetime保证金使用时间
//        , 'use_type' => 2 //smallint(3)保证金应用类型 冻结出价保证金
//        , 'use_detail' => $msg //text应用明细
//        , 'occur_money' => $occur_money //double(10,2)发生金额
//        , 'remain_amount' => $remain_amount  //余额
//        , 'createtime' => $now //datetime创建时间
//        );
//        $log_id = $bail_log->add($bail_log_info);
//
//        //更新车商保证金
//        $up_info = array();
//        $up_info['freeze_amount'] = ($dealer_info['freeze_amount'] + $occur_money);
//        $up_info['bail_amount'] = $remain_amount;
//        $eff = M('car_dealer')->where(" dealer_id='{$dealer_id}' ")->save($up_info);
//        if (!(intval($eff) > 0)) {
//            AuctionException::make_throw('500052');
//        }
//
//
//        return true;
    }

    /**
     * 解东拍单所有冻结的保证金
     */
    public static function free_all($order_id)
    {
        $dealers = M('dealer_bail_log')->where(array("order_id" => $order_id, "use_type" => 2, "is_free" => 0))->select();
        foreach ($dealers as $key => $val) {
            $newDealers[] = $val['dealer_id'];
        }
        if (!empty($newDealers)) {
            $bail = new ThriftBailService();
            $bail_state = $bail->unfreezeBail(implode(',', $newDealers), $order_id);
            if ($bail_state->code != '000000') {
                AuctionException::make_throw('500074'); //解冻保证金出错
            }
        }
        return true;
//        $m = M();
//        $sql = "call `paimai_refund`('{$order_id}' ,'0');";
//        try {
//            $r = $m->execute($sql);
//        } catch (AuctionException $ex) {
//            AuctionException::make_throw('500074'); //解冻保证金出错
//        }
//        return true;
    }

    /**
     * 解冻拍单的其它车商的保证金
     *
     * @param 车商id
     * @param int  order_id 使用保证金的拍单id
     * @param $msg 保证金使用描述
     *
     * @return true/false   成功、失败
     */
    public function free($order_id, $msg = '解冻保证金')
    {

        $dealer_id = $this->dealer_id;
        $dealers = M('dealer_bail_log')->where(array("order_id" => $order_id, "use_type" => 2, "is_free" => 0))->where("dealer_id !=" . $dealer_id)->select();
        foreach ($dealers as $key => $val) {
            $newDealers[] = $val['dealer_id'];
        }
        if (!empty($newDealers)) {
            $bail = new ThriftBailService();
            $bail_state = $bail->unfreezeBail(implode(',', $newDealers), $order_id);
            if ($bail_state->code != '000000') {
                return false;
            }
        }
        return true;
//        $m = M();
//        $sql = "call `paimai_refund`('{$order_id}' ,'{$dealer_id}' );";
//        $r = $m->execute($sql);
//        return true;


        /* if( !is_numeric($order_id) || $order_id<=0 ){
          AuctionException::make_throw('500055');
          }
          $dealer_id = $this->dealer_id;
          $now = date("Y-m-d H:i:s",time());

          $bail_log = M('dealer_bail_log');
          $info = $bail_log->query("SELECT SUM(IF(use_type=2,occur_money,0)) AS freeze_amount,SUM(IF(use_type=3,occur_money,0)) AS free_amount FROM au_dealer_bail_log WHERE dealer_id='{$dealer_id}' and order_id='{$order_id}';");
          if($info && ($info[0]['freeze_amount']==$info[0]['free_amount'])){
          //是否已经解冻
          return true;
          }

          $info = $bail_log->field('bl_id,occur_money,use_time')->where("dealer_id='{$dealer_id}' and order_id='{$order_id}' and use_type=2")->find();
          $occur_money = $info['occur_money'];
          $use_time = $info['use_time'];
          if(!$occur_money){
          AuctionException::make_throw('500051'); //未发现冻结记录
          }

          //车商信息
          $dealer = new Dealer($dealer_id);
          $dealer_info = $dealer->dealer_base_info();
          $db_freeze_amount = $dealer_info['freeze_amount'];
          $new_freeze_price = ($db_freeze_amount-$occur_money);
          if($new_freeze_price<0 || $new_freeze_price>$dealer_info['bail_amount']){
          AuctionException::make_throw('500054'); //保证金不能超过保证金总数，并且不能小于0
          }

          //更新冻结保证金
          $up_info = array();
          $up_info['freeze_amount'] = $new_freeze_price;
          $eff = M('car_dealer')->where("dealer_id='{$dealer_id}' and freeze_amount='{$db_freeze_amount}'")->save($up_info);
          if(!(intval($eff)>0)){
          AuctionException::make_throw('500052');
          }

          //生成冻结描述
          $row = M()->query("SELECT CONCAT('解冻出价保证金，  拍品【',pad.`city_name`,ad.`city_name`,'】 ',mb.`name` ,' ',s.`name` ,m.`name`,' 。') msg
          FROM  au_order o
          LEFT JOIN au_cars car ON car.car_id = o.`car_id`
          LEFT JOIN au_addr_area ad ON car.reg_city=ad.city_code
          LEFT JOIN au_addr_area pad ON ad.pid=pad.city_code
          LEFT JOIN au_car_model m ON car.`model_id` = m.`model_id`
          LEFT JOIN `au_car_series` s ON m.`series_id` = s.`series_id`
          LEFT JOIN au_car_brand b ON s.`brand_id` = b.`brand_id`
          LEFT JOIN au_car_mbrand mb ON b.`mbrand_id` = mb.`mbrand_id`
          WHERE  o.`order_id` = {$order_id} ;");
          if(count($row)>0){
          $msg = $row[0]['msg'];
          }

          //保证金使用记录
          $bail_log_info = array(
          'dealer_id'=>$dealer_id //int(10)车商id
          ,'order_id'=>$order_id //int(10)拍单号
          ,'use_time'=>$use_time //datetime保证金使用时间
          ,'use_type'=>3 //smallint(3)保证金应用类型 冻结出价保证金
          ,'use_detail'=>$msg //text应用明细
          ,'occur_money'=>$occur_money //double(10,2)发生金额
          ,'remain_amount'=>$dealer_info['bail_amount']  //余额
          ,'createtime'=>$now //datetime创建时间
          ,'free_bl_id'=>$info['bl_id']
          );
          $log_id = $bail_log->add($bail_log_info);
          return true;
         */
    }

    /**
     * 提取保证金
     *
     * @param int $occur_money 发生金额
     * @param string $msg 描述
     *
     * @return true/false
     */
    public function extract($occur_money, $msg = '提取保证金')
    {
        return $this->deduct($occur_money, 1, '', $msg);
    }

    /**
     * 争议支出保证金
     *
     * @param int $occur_money 发生金额
     * @param int $order_id 相关拍单号
     * @param string $msg 描述
     *
     * @return true/false
     */
    public function dispute_pay($occur_money, $order_id, $msg = '争议支出保证金')
    {
        return $this->deduct($occur_money, 2, $order_id, $msg);
    }

    /**
     * 赔付保证金
     *
     * @param int $occur_money 发生金额
     * @param int $order_id 相关拍单号
     * @param string $msg 描述
     *
     * @return true/false
     */
    public function compensate($occur_money, $order_id, $msg = '违约赔付保证金')
    {
        return $this->deduct($occur_money, 3, $order_id, $msg);
    }

    /**
     * 扣除车商保证金
     *
     * @param int $occur_money 发生金额
     * @param int $de_type 1提取 2争议支出 3违约赔付
     * @param int $order_id 拍单号
     * @param string $msg 描述
     *
     * @return true/false
     */
    private function deduct($occur_money, $de_type, $order_id, $msg = '')
    {
        $dealer_id = $this->dealer_id;

        if (!is_numeric($dealer_id) || $dealer_id <= 0) {
            AuctionException::make_throw('500001');
        }
        if (!is_numeric($occur_money) || $occur_money <= 0) {
            AuctionException::make_throw('500004');
        }

        $use_types = array(1 => 4, 2 => 5, 3 => 6);
        if (!array_key_exists($de_type, $use_types)) {
            AuctionException::make_throw('500056');
        }
        $dealer = M('car_dealer');
        $now = date("Y-m-d H:i:s", time());
        $info = $dealer->field('bail_amount')->where("dealer_id='{$dealer_id}'")->find();
        $bail_amount = $info['bail_amount'];
        if ($occur_money > $bail_amount) {
            AuctionException::make_throw('500051'); //保证金不足
        }

        $user_info = session('user_info');

        M()->startTrans();
        $collectionData = [
            'payment_type' => 5, //收款类型 保证金充值
            'payment_method' => 1,
            'amount' => $occur_money,
            'status' => 1,
            'create_time' => $now,
            'update_time' => $now,
            'emp_id' => $user_info['emp_id'],
            'emp_name' => $user_info['real_name'],
        ];
        $collection_id = Collection::add($collectionData);
        if ($collection_id < 1) {
            Log::record("保证金充值，添加收款单失败,车商ID[$dealer_id]", "ERR", true);
            M()->rollback();
            AuctionException::make_throw('500067');
        }

        $bail = new ThriftBailService();
        $bail_state = $bail->decBail($dealer_id, $occur_money, $use_types[$de_type], $msg, $order_id, 0, 0, $collection_id);
        if ($bail_state->code == '000000') {
            if ($use_types[$de_type] == 5 || $use_types[$de_type] == 6) {
                //增加累计赔付总数
                $dealer->where("dealer_id='{$dealer_id}'")->setInc('indemnity_amount', $occur_money);
            }
            M()->commit();
            return true;
        }

        return false;
    }

    /**
     * 保证金消费记录
     * @param int $dealer_id
     * @param int $occur_money
     * @param int $remain_amount
     * @param int $collection_id
     * @param int string $use_detail
     * @return mixed
     */
    public static function pay_money($dealer_id, $occur_money, $remain_amount, $collection_id, $use_detail = '车辆维保信息查询透资，金额扣除。')
    {
        $bail_log = M('dealer_bail_log');
        $time = date('Y-m-d H:i:s');
        $data = array(
            'dealer_id' => $dealer_id,
            'use_time' => $time,
            'createtime' => $time,
            'use_type' => 8,
            'use_detail' => $use_detail,
            'occur_money' => $occur_money,
            'remain_amount' => $remain_amount,
            'collection_id' => $collection_id
        );
        return $bail_log->add($data);
    }

    /**
     * 保证金中扣除车商违约金
     *
     * @param array $data
     *
     * @return true/false
     */
    public function occurViolate($data = array())
    {
        $dealer_id = $this->dealer_id;

        if (!is_numeric($data['order_id']) || $data['order_id'] <= 0) {
            AuctionException::make_throw('700027');
        }

        if (!is_numeric($data['dealer_id']) || $data['dealer_id'] <= 0) {
            AuctionException::make_throw('500001');
        }

        if (!is_numeric($data['occur_money']) || $data['occur_money'] < 0) {
            AuctionException::make_throw('1700003');
        }

        //获取车商保证金信息
        $dealerObj = new \AuctionCore\CarDealer\Dealer($data['dealer_id']);
        $dealerInfo = $dealerObj->detail();
        if (empty($dealerInfo)) {
            AuctionException::make_throw('500012'); //获取车商异常
        }

        $bail = new ThriftBailService();
        $bail_state = $bail->unfreezeDecBail($dealer_id, $data['order_id'], $data['occur_money'], 5, $data['use_detail']);
        if ($bail_state->code == '000000') {
            return true;
        } else {
            Log::record($bail_state['code']."-".$bail_state['message'],"ERR",true);
            return false;
        }

//        // 检查冻结保证金是否足够扣除
//        $bail_log = M('dealer_bail_log');
//        $bailCond = array(
//            'dealer_id' => $data['dealer_id'],
//            'order_id' => $data['order_id'],
//            'use_type' => 2, //保证金应用类型 1充值 2冻结出价保证金 3解冻出价保证金 4提取 5争议支出 6违约赔付 7其它
//            'is_free' => 0, // 若为冻结记录时，标识是否已解冻 ，1解冻，0未解冻_
//        );
//        $info = $bail_log->field('*')->where($bailCond)->find();
//
//        if (empty($info)) {
//            AuctionException::make_throw('500053'); //保证金记录不存在
//        }
//
//        if ($data['occur_money'] > $info['occur_money']) {
//            AuctionException::make_throw('500051'); //冻结保证金不足
//        }
//
//        $freezeAmount = $info['occur_money']; // 冻结保证金额度
//        $extraAmount = $freezeAmount - $data['occur_money']; // 当前要解冻的保证金额度
//        $remainAmount = $dealerInfo['bail_amount'] + $extraAmount; // 可用保证金总额
//
//
//        $now = date("Y-m-d H:i:s", time());
//        //添加保证金扣款记录
//        $bail_log_info = array(
//            'dealer_id' => $data['dealer_id'] //int(10)车商id
//        , 'order_id' => $data['order_id'] //int(10)拍单号
//        , 'use_type' => 5 //保证金应用类型 1充值 2冻结出价保证金 3解冻出价保证金 4提取 5争议支出 6违约赔付 7其它
//        , 'use_detail' => $data['use_detail'] //text应用明细
//        , 'occur_money' => $data['occur_money'] //double(10,2)发生金额
//        , 'remain_amount' => $dealerInfo['bail_amount']//余额
//        , 'createtime' => $now //datetime创建时间
//        , 'use_time' => $now //datetime保证金使用时间
//        , 'free_bl_id' => $info['bl_id'] //datetime保证金使用时间
//        );
//        $resOccur = $bail_log->add($bail_log_info);
//
//        //添加保证金解冻记录
//        $bail_log_info = array(
//            'dealer_id' => $data['dealer_id'] //int(10)车商id
//        , 'order_id' => $data['order_id'] //int(10)拍单号
//        , 'use_type' => 3 //保证金应用类型 1充值 2冻结出价保证金 3解冻出价保证金 4提取 5争议支出 6违约赔付 7其它
//        , 'use_detail' => "扣除冻结保证金，拍品【{$data['order_no']}, {$data['order_id']}】  。" //text应用明细
//        , 'occur_money' => $extraAmount //double(10,2)发生金额
//        , 'remain_amount' => $remainAmount  //余额
//        , 'createtime' => $now //datetime创建时间
//        , 'use_time' => $now //datetime保证金使用时间
//        , 'free_bl_id' => $info['bl_id'] //datetime保证金使用时间
//        );
//        $resExtra = $bail_log->add($bail_log_info);
//
//        // 更新冻结保证金记录，修改为已解冻状态
//        $bail_log_info = array(
//            'is_free' => 1
//        );
//        $resFixStatus = $bail_log->where($bailCond)->save($bail_log_info);
//        if ($resOccur !== false && $resFixStatus !== false && $resExtra !== false) {
//            // 更新车商表
//            $dealerParams = array(
//                'bail_amount' => $remainAmount,
//                'freeze_amount' => $dealerInfo['freeze_amount'] - $freezeAmount,
//                'indemnity_amount' => $dealerInfo['indemnity_amount'] + $data['occur_money'],
//            );
//            $resDealer = $dealerObj->updateDealer($dealerParams);
//            if ($resDealer !== false) {
//                return true;
//            }
//        }
//        return false;
    }

    /**
     * 推送收银台数据
     * @param $collection_no
     * @param $amount
     * @return mixed
     */
    public static function collection_log($collection_no, $amount, $type)
    {
        $collection_log = M('collection');
        $time = date('Y-m-d H:i:s');
        $data = array(
            'collection_no' => $collection_no,
            'status' => 1,
            'payment_type' => $type,
            'payment_method' => 1,
            'amount' => $amount,
            'emp_id' => 1,
            'emp_name' => '系统管理员',
            'create_time' => $time,
            'update_time' => $time
        );
        return $collection_log->add($data);
    }

    /**
     * @param int $dealer_id 车商ID
     * @param int $order_id 拍单ID
     * @param string $use_detail 使用详情
     * @return bool
     */
    public static function unfreeze($dealer_id, $order_id)
    {

        $bail = new ThriftBailService();
        $bail_state = $bail->unfreezeBail($dealer_id, $order_id);
        if ($bail_state->code == '000000') {
            return true;
        } else {
            Log::record("解冻保证金失败，车商ID[$dealer_id],ERROR_CODE:". $bail_state->code . "ERROR_MSG:" . $bail_state->message, "ERR", true);
            return false;
        }
//        $map = [
//            'dealer_id' => $dealer_id,
//            'order_id' => $order_id,
//            'use_type' => 2,
//            'is_free' => 0
//        ];
//        $bail = M('dealer_bail_log');
//        $info = $bail->where($map)->find();
//        if (empty($info)) {
//            Log::record("解冻保证金: 保证金记录不存在");
//            return false;
//        }
//        //获取车商保证金信息
//        $dealerObj = new Dealer($dealer_id);
//        $dealerInfo = $dealerObj->detail();
//        if (empty($dealerInfo)) {
//            Log::record("解冻保证金: 获取车商异常");
//            return false;
//        }
//        $amount = $info['occur_money'];
//        $now = date("Y-m-d H:i:s", time());
//        $remainAmount = $dealerInfo['bail_amount'] + $amount; // 可用保证金总额
//        //添加解冻记录
//        $data = [
//            'dealer_id' => $dealer_id,
//            'order_id' => $order_id,
//            'use_type' => 3,
//            'use_detail' => "解冻出价保证金",
//            'occur_money' => $amount,
//            'remain_amount' => $remainAmount,
//            'createtime' => $now,
//            'use_time' => $now,
//            'free_bl_id' => $info['bl_id'],
//        ];
//        $res = $bail->add($data);
//        if (!$res) {
//            Log::record("解冻保证金: 添加解冻记录失败");
//            return false;
//        }
//        //更新冻结记录
//        $resUpdate = $bail->where(['bl_id' => $info['bl_id']])->save(['is_free' => 1, 'free_bl_id' => $res]);
//        if (!$resUpdate) {
//            Log::record("解冻保证金: 更新解冻记录失败");
//            return false;
//        }
//        //更新车商信息
//        $dealerParams = array(
//            'bail_amount' => $remainAmount,
//            'freeze_amount' => $dealerInfo['freeze_amount'] - $amount,
//        );
//        $resDealer = $dealerObj->updateDealer($dealerParams);
//        if (!$resDealer) {
//            Log::record("解冻保证金: 更新车商信息失败");
//            return false;
//        }
//        return true;
    }


    /**获取最新日志log ID
     * @param $dealer_id
     * @param $occur_money
     * @param $user_type
     * @return mixed
     */
    public static function last_bail_log($dealer_id, $occur_money, $user_type)
    {
        $bail_log = M('dealer_bail_log')->where(array('dealer_id' => $dealer_id, 'occur_money' => $occur_money, 'use_type' => $user_type))->order('bl_id desc')->find();
        if ($bail_log) {
            return $bail_log['bl_id'];
        }
        return 0;
    }

}

